package com.wi.demo;

import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
@Scope("request")
public class HomeController {
	@Autowired
	private User user;
	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model, HttpServletRequest request) {
		User existingUser = (User) request.getSession().getAttribute("user");
		if (existingUser != null && !!existingUser.isLoggedin()) {
			user.setAlreadyLoggedIn(true);
			return login(locale, existingUser, model, request);
		} else {
			String uuid = UUID.randomUUID().toString().replaceAll("-","");
			model.addAttribute("user", new User("edward", "123456", uuid,
					false));
			return "home";
		}

	}

	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public String logout(Locale locale, User user, Model model,
			HttpServletRequest request) {
		user.setLoggedin(false);
		request.getSession().removeAttribute("user");
		return "redirect:/";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Locale locale, User user, Model model,
			HttpServletRequest request) {
		user.setLoggedin(true);
		model.addAttribute("user", user);
		request.getSession().setAttribute("user", user);
		return "loggedin";
	}

}
